//
//  OAuthViewController.swift
//  Weibo(Swift)
//
//  Created by 阳 on 16/7/11.
//  Copyright © 2016年 阳. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {
    lazy var webView : UIWebView = {
        let webView = UIWebView()
        webView.scrollView.bounces = false
        webView.delegate = self
        return webView
    }()
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        
       setupUI()
       loadWebView()
    }
   
}

extension OAuthViewController
{
    func setupUI()
    {
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "didClcikBack")
    }
    func loadWebView()
    {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=585609419&redirect_uri=https://www.baidu.com"
        let request = NSURLRequest(URL: NSURL(string: urlString)!)
        webView.loadRequest(request)

    }
    func didClcikBack()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}
// MARK: - WebView代理
extension OAuthViewController : UIWebViewDelegate
{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let absoluteString = request.URL?.absoluteString
        
        guard let absoluteStringTemp = absoluteString where absoluteStringTemp.hasPrefix(redirectURL) else
        {
            return true
        }
        
        let query = request.URL?.query
        
        guard let queryTemp = query where queryTemp.hasPrefix("code=") else
        {
            dismissViewControllerAnimated(true, completion: nil)
            return false
        }
        
        let code = queryTemp.substringFromIndex("code=".endIndex)
        NetworkManager.sharedManager.requestAccessToken(code) { (response) -> Void in
            
            guard var access_token_dic = response else{
                
                self.dismissViewControllerAnimated(true, completion: nil)
                return
            }
            NetworkManager.sharedManager.requestUserAccount(access_token_dic["access_token"]! as! String, uid: access_token_dic["uid"]! as! String, callBack: { (response) -> Void in
                
                guard let userAccountDic = response else
                {
                    self.dismissViewControllerAnimated(true, completion: nil)
                    return
                }
//                access_token_dic["screen_name"] = userAccountDic["screen_name"]
//                access_token_dic["avatar_large"] = userAccountDic["avatar_large"]
                for (key, _) in userAccountDic
                {
                    access_token_dic[key] = userAccountDic[key]
                    print(access_token_dic[key])
                }
                UserAccount.shareUserAccount.saveUserAccount(access_token_dic)
                
              //发送登录成功通知
            NSNotificationCenter.defaultCenter().postNotificationName(loginSuccessNotification, object: nil)
                
                delay(1, action: { () -> Void in
                   self.dismissViewControllerAnimated(true, completion: nil)
                    
                })
            })
            
        }
        
        return false
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value='\(userName)';document.getElementById('passwd').value='\(userPassword)';")
        
    }
    
}